package com.wjboot.wxminiapp.util;

import cn.binarywang.wx.miniapp.config.WxMaConfig;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author manlu
 */
@Configuration
public class SenInfoCheckUtil {
    private static WxMaConfig config;


    @Value("${wx.miniapp.appid}")
    private String appId;

    @Value("${wx.miniapp.secret}")
    private String secret;


    /**
     * 图片违规检测,对外提供,直接使用
     *
     * @param file
     * @return
     */
    public static Boolean imgFilter(MultipartFile file, String accessToken) {
        String contentType = file.getContentType();
        return checkPic(file, accessToken, contentType);
    }

    /**
     * 文本违规检测,对外提供,直接使用
     *
     * @param content
     * @return
     */
    public static Boolean cotentFilter(String accessToken, String content) {
        return checkContent(accessToken, content);
    }

    /**
     * 校验图片是否有敏感信息
     *
     * @param multipartFile
     * @return
     */
    private static Boolean checkPic(MultipartFile multipartFile, String accessToken, String contentType) {
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            HttpPost request = new HttpPost("https://api.weixin.qq.com/wxa/img_sec_check?access_token=" + accessToken);
            request.addHeader("Content-Type", "application/octet-stream");
//            InputStream inputStream = multipartFile.getInputStream();
            InputStream inputStream = compressImage(multipartFile);
            byte[] byt = new byte[inputStream.available()];
            inputStream.read(byt);
            request.setEntity(new ByteArrayEntity(byt, ContentType.create(contentType)));
            response = httpclient.execute(request);
            HttpEntity httpEntity = response.getEntity();
            String result = EntityUtils.toString(httpEntity, "UTF-8");// 转成string
            JSONObject jso = JSONUtil.parseObj(result);
            return getResult(jso);
        } catch (Exception e) {
            e.printStackTrace();
            return true;
        }
    }


    /**
     * 压缩图片
     *
     * @param multipartFile
     */
    public static InputStream compressImage(MultipartFile multipartFile) {
        //*************对不是jpg格式的图片转换成jpg格式***************

        //获取文件名后缀，判断其格式
        int begin = multipartFile.getOriginalFilename().lastIndexOf(".");
        int last = multipartFile.getOriginalFilename().length();
        //获得文件后缀名
        String houzuiFileName = multipartFile.getOriginalFilename().substring(begin, last);

        //创建临时文件
        File tempFile = new File(multipartFile.getOriginalFilename());
        //写入临时File文件 tempFile，将multipartFile转换成File
        try {
            //import org.apache.commons.io.FileUtils;
            FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), tempFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //如果文件不是jpg格式,转换其格式
        if (!"jpg".equalsIgnoreCase(houzuiFileName)) {
            //ImageUtils是一个工具类，下面给出
            //将png格式转换成jpg，输出到tempFile
            ImageUtils.convert(multipartFile.getOriginalFilename(), "jpg", tempFile.getAbsolutePath());//测试OK
            //*************对不是jpg格式的图片转换成jpg格式***************
        }
        try {
            //压缩图片
            BufferedImage bufferedImage = Thumbnails.of(tempFile)
//                .size(740, 1330)//指定压缩之后的图片尺寸
                .scale(1f)
                .outputQuality(0.8f)//图片压缩质量
                .asBufferedImage();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "jpg", os);
            InputStream inputStream = new ByteArrayInputStream(os.toByteArray());
//            System.out.println(inputStream);
            return inputStream;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
//             会在本地产生临时文件，用完后需要删除
            if (tempFile.exists()) {
                tempFile.delete();
            }
        }
        return null;
    }

    /**
     * 校验内容是否有敏感信息
     *
     * @param content
     * @return
     */
    private static Boolean checkContent(String accessToken, String content) {
        Map<String, Object> paramMap = new HashMap<String, Object>(1);
        paramMap.put("content", content);
        Object result = HttpUtil.post("https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + accessToken, JSONUtil.toJsonPrettyStr(paramMap));
        JSONObject jsonObject = JSONUtil.parseObj(result);
        System.out.println(jsonObject);
        return getResult(jsonObject);
    }

    /**
     * 返回状态信息,可以修改为自己的逻辑
     *
     * @param jso
     * @return
     */
    private static Boolean getResult(JSONObject jso) {
        Object errcode = jso.get("errcode");
        int errCode = (int) errcode;
        if (errCode == 0) {
            return true;
        } else if (errCode == 87014) {
            return false;
        } else {
            return false;
        }
    }

    /**
     * 功能描述： 获取access_token,每隔7000s获取一次
     * 获取小程序的 access_token
     *
     * @return
     */
//    @Scheduled(fixedDelay = 2 * 3000 * 1000)
//    public void getAccessToken() {
////        System.out.println(appId);
////        System.out.println(secret);
////        // 从缓存中获取
////        String accessToken = String.valueOf(RedisUtils.getCacheObject("access_token"));
////        if (!StringUtils.isEmpty(accessToken) && !"null".equals(accessToken)) {
//////            return accessToken;
////        }
////        String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret;
////        String result = HttpUtil.get(accessTokenUrl);
////        JSONObject json = JSONUtil.parseObj(result);
////        String access_token = String.valueOf(json.get("access_token"));
////        Long expires_in = Long.valueOf(String.valueOf(json.get("expires_in")));
////        if (StringUtils.isEmpty(access_token)) {
////            access_token = "";
////        }
////        System.out.println("json:" + json.toString());
////        // 存redis, 过期时间为7200秒
////        RedisUtils.setCacheObject("access_token", access_token, Duration.ofSeconds(expires_in));
////        return access_token;
//        WxMaConfig configStorage = this.wxService.getWxMaConfig();
//        String token = configStorage.getAccessToken();
//        SenInfoCheckUtil.accessTokenMap.put(SenInfoCheckUtil.ACCESS_TOKEN_KEY, token);
//    }

    /**
     * 接口调用凭证 access_token
     *
     * @return
     */
//    public String getAccessToken() {
//        // 从缓存中获取
//        String accessToken = String.valueOf(RedisUtils.getCacheObject("access_token"));
//        if (!StringUtils.isEmpty(accessToken) && !"null".equals(accessToken)) {
//            return accessToken;
//        }
//        String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret;
//        String result = HttpUtil.get(accessTokenUrl);
//        JSONObject json = JSONUtil.parseObj(result);
//        String access_token = String.valueOf(json.get("access_token"));
//        Long expires_in = Long.valueOf(String.valueOf(json.get("expires_in")));
//        if (StringUtils.isEmpty(access_token)) {
//            access_token = "";
//        }
//        System.out.println("json:" + json.toString());
//        // 存redis, 过期时间为7200秒
//        RedisUtils.setCacheObject("access_token", access_token, Duration.ofSeconds(expires_in));
//        return access_token;
//    }
}
